import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { loginApi } from '@/api/user';
import type { User, LoginData } from '@/types/user';

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref<string | null>(uni.getStorageSync('token') || null);
    const userInfo = ref<User | null>(JSON.parse(uni.getStorageSync('userInfo') || 'null'));

    const isLoggedIn = computed(() => !!token.value);

    const login = async (loginData: LoginData) => {
      const res = await loginApi(loginData);
      // 根据API返回结构，数据在res.data中
      const { token: newToken, admin: newUserInfo } = res;

      token.value = newToken;
      userInfo.value = newUserInfo;

      uni.setStorageSync('token', newToken);
      uni.setStorageSync('userInfo', JSON.stringify(newUserInfo));
    };

    const logout = () => {
      token.value = null;
      userInfo.value = null;
      uni.removeStorageSync('token');
      uni.removeStorageSync('userInfo');
    };

    return { token, userInfo, login, logout, isLoggedIn };
  },
  {
    persist: false,
  }
);